package com.rogerfan.easy.shiro;

import java.util.Collection;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationListener;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


import com.rogerfan.easy.shiro.filter.AppUserNameToken;
import com.rogerfan.easy.web.util.WebUtil;


@Component("tokenListener")
public class TokenLoginListener implements AuthenticationListener {
	private static final Logger log = LoggerFactory
			.getLogger(TokenLoginListener.class);
	@Autowired
	ShiroTokenManager tokenManager;
	@Autowired
	UserCache userCache;
	
	@Override
	public void onSuccess(AuthenticationToken token, AuthenticationInfo info) {
		ShiroUtils.getRequest().setAttribute(AppUserNameToken.REQUEST_TOKEN, token);
		@SuppressWarnings("unchecked")
		Collection<String> realms = info.getPrincipals().asList();
		if (realms != null && !realms.isEmpty()) {
			String  principal = (String) realms.iterator().next();
			Long userId =ShiroUtils.getUserFormPrincipal(principal).getId();
			if(userId != null){
				userCache.save(userId);
			}
			
			
		}
		
		
	}

	@Override
	public void onFailure(AuthenticationToken token, AuthenticationException ae) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onLogout(PrincipalCollection principals) {
		tokenManager.remove(ShiroUtils.getSession().getId().toString());
		
	}

	

}
